package com.zxt.te.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxt.te.dao.UserMapper;
import com.zxt.te.model.User;
import com.zxt.utils.ZXTCollectionsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserManager extends ServiceImpl<UserMapper, User> {

    public User getByUserName(String username) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getUserName, username);
        return getOne(wrapper);
    }


    public User getByWxOpenId(String wxOpenId) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getWxOpenId, wxOpenId);
        return getOne(wrapper);
    }

    /**
     * 查询已经存在的用户名、手机号、邮箱、昵称
     *
     * @param username
     * @param phone
     * @param email
     * @param nickName
     * @return
     */
    public User getByUserNameOrPhoneOrEmailOrNickName(String username, String phone, String email, String nickName) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getUserName, username).or().eq(User::getPhone, phone).or().eq(User::getEmail, email).or().eq(User::getNickName, nickName);
        List<User> list = list(wrapper);
        if (ZXTCollectionsUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }


    public void bindWxOpenIdByUserName(String userName, String openId) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getWxOpenId, openId);
        wrapper.eq(User::getUserName, userName);
        update(wrapper);
    }

    /**
     * 增加会员成长值
     *
     * @param userId         用户id
     * @param oldGrowthValue 原有的成长值
     * @param num            本次新增的数值
     * @return
     */
    public boolean addGrowthValue(Long userId, Integer oldGrowthValue, Integer num) {
        final LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.setSql("growth_value = growth_value + " + num);
        wrapper.eq(User::getId, userId);
        wrapper.eq(User::getGrowthValue, oldGrowthValue);
        return update(wrapper);
    }

    /**
     * 修改用户昵称
     *
     * @param userId
     * @param nickName
     */
    public void updateNickName(Long userId, String nickName) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getNickName, nickName);
        wrapper.eq(User::getId, userId);
        update(wrapper);
    }

    /**
     * 根据昵称获取用户信息
     *
     * @param nickName
     * @return
     */
    public User getByNickName(String nickName) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getNickName, nickName);
        return getOne(wrapper);
    }
}
